<?php
namespace app\common\model;

use org\util\TreeUtil;

class AuthRuleModel extends BaseModel
{
    protected $name = 'auth_rule'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改
    protected $type = [];

    protected function getStatusTextAttr($value, $data)
    {
        $status = [0 => '<span class="label label-warning">关闭</span>',
                   1 => '<span class="label label-primary">开启</span>'];
        return $status[$data['status']];
    }

    protected function getIsmenuTextAttr($value, $data)
    {
        $status = [0 => '<span class="label label-warning">不显示</span>',
                   1 => '<span class="label label-primary">显示</span>'];
        return $status[$data['ismenu']];
    }

    /**
     * 缓存权限规则
     * @param $utype
     */
    public function updateCache($utype)
    {
        $list = $this->where('status', 1)->where('utype', $utype)->order('rule_sort asc')->select();
        $list = obj2array($list, ['status_text', 'ismenu_text']);
        $tree = TreeUtil::tree($list, 'title', 'rule_id', 'rule_pid');
        $data = [];
        foreach ($tree as $v) {
            $isSon               = TreeUtil::hasChild($tree, $v['rule_id'], 'rule_pid');
            if(!empty($v['controller']) && !empty($v['action'])){
                $v['url'] = url("{$v['module']}/{$v['controller']}/{$v['action']}",$v['condition']);
            }else{
                $v['url'] = 'javascript:;';
            }
            $v['is_son']         = $isSon;
            $data[$v['rule_id']] = $v;
        }
        if (cache('auth_rule_' . $utype, $data)) {
            return true;
        } else {
            return false;
        }
    }
}




